package com.bcx.crm.spring_boot.springMVC.myInterceptor;

import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * Created by ys on 2018/4/21.
 * 核心 : 拦截器是对每一个请求(符合拦截器配置--对应的请求路径--路径对应的目标方法)的前后进行相关的业务处理
 * 自定义拦截器 : 普通的bean实现HandlerInterceptor接口，或者，继承HandlerInterceptorAdapter类
 */
public class DemoInterceptor implements HandlerInterceptor{
    @Override   //请求方法前执行
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        long timeMillis = System.currentTimeMillis();
        request.setAttribute("startTime",timeMillis);
        return true;
    }

    @Override   //请求方法后执行
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {
        long startTime =(Long) request.getAttribute("startTime");
        long endTime = System.currentTimeMillis();
        System.out.println("本次请求处理时间是:"+(endTime-startTime));
        request.removeAttribute("startTime");
        request.setAttribute("handling",endTime-startTime);
    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception e) throws Exception {
        System.err.println(handler);
        System.err.println(e);
    }
}
